package com.chujian.framework.starter.log.trace;

import com.chujian.framework.starter.log.properties.TraceLogProperties;
import feign.RequestInterceptor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * feign拦截器，传递traceId
 *
 * @author chujian
 * @since 2021-12-13
 */
@Configuration
@ConditionalOnClass(value = {RequestInterceptor.class})
public class OpenFeignTraceConfig {
    @Resource
    private TraceLogProperties traceProperties;

    @Bean
    public RequestInterceptor feignTraceInterceptor() {
        return template -> {
            if (traceProperties.getEnabled()) {
                //传递日志traceId
                String traceId = MDCTraceUs.getTraceId();
                if (StringUtils.isNotEmpty(traceId)) {
                    template.header(MDCTraceUs.TRACE_ID_HEADER, traceId);
                    template.header(MDCTraceUs.SPAN_ID_HEADER, MDCTraceUs.getSpanId());
                }
            }
        };
    }
}
